/*
 * @Author: 小豪
 * @Description:
 * @Date: 2024-04-29 17:15:13
 * @LastEditTime: 2024-05-23 20:31:32
 * @FilePath: \bsct\gohub\app\http\controllers\api\v1\users_controller.go
 */
package v1

import (
	"gohub/app/models/user"
	"gohub/app/requests"
	"gohub/pkg/auth"
	"gohub/pkg/config"
	"gohub/pkg/file"
	"gohub/pkg/response"
	"time"

	"github.com/gin-gonic/gin"
)

type UsersController struct {
	BaseAPIController
}

// CurrentUser 当前登录用户信息
func (ctrl *UsersController) CurrentUser(c *gin.Context) {
	userModel := auth.CurrentUser(c)
	response.Data(c, userModel)
}

// Index 所有用户
func (ctrl *UsersController) Index(c *gin.Context) {
	request := requests.PaginationRequest{}
	errs := requests.Validate(c, &request, requests.Pagination)
	if len(errs) > 0 {
		// 失败，显示错误提示
		response.JSON(c, gin.H{
			"success":    false,
			"total_page": "",
			"status":     "100",
			"msg":        errs,
			"data":       map[string]string{},
			"time":       time.Now().Unix(),
		})
		return
	}
	data, pager := user.Paginate(c, 10)
	response.JSON(c, gin.H{
		"success":    true,
		"total_page": pager.TotalPage,
		"status":     "200",
		"msg":        "成功！",
		"data":       data,
		"time":       time.Now().Unix(),
	})
}
func (ctrl *UsersController) UpdateProfile(c *gin.Context) {

	request := requests.UserUpdateProfileRequest{}
	errs := requests.Validate(c, &request, requests.UserUpdateProfile)
	if len(errs) > 0 {
		// 失败，显示错误提示
		response.JSON(c, gin.H{
			"success":    false,
			"total_page": "",
			"status":     "100",
			"msg":        errs,
			"data":       map[string]string{},
			"time":       time.Now().Unix(),
		})
		return
	}
	currentUser := auth.CurrentUser(c)
	currentUser.Name = request.Name
	currentUser.City = request.City
	currentUser.Introduction = request.Introduction
	rowsAffected := currentUser.Save()
	if rowsAffected > 0 {
		response.Data(c, currentUser)
	} else {
		response.Abort500(c, "更新失败，请稍后尝试~")
	}
}
func (ctrl *UsersController) UpdateAvatar(c *gin.Context) {

	request := requests.UserUpdateAvatarRequest{}
	errs := requests.Validate(c, &request, requests.UserUpdateAvatar)
	if len(errs) > 0 {
		// 失败，显示错误提示
		response.JSON(c, gin.H{
			"success":    false,
			"total_page": "",
			"status":     "100",
			"msg":        errs,
			"data":       map[string]string{},
			"time":       time.Now().Unix(),
		})
		return
	}

	avatar, err := file.SaveUploadAvatar(c, request.Avatar)
	if err != nil {
		response.Abort500(c, "上传头像失败，请稍后尝试~")
		return
	}

	currentUser := auth.CurrentUser(c)
	currentUser.Avatar = config.GetString("app.url") + avatar
	currentUser.Save()

	response.Data(c, currentUser)
}
